<template>
  <div>
    <el-tabs v-model="activeName">
      <el-tab-pane label="管理" name="manage">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="状态" prop="configKey">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="私有" value="0"></el-option>
              <el-option label="公开" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间" prop="status">
            <el-date-picker
              v-model="queryParams.dateRange"
              el-date-picker
              placeholder="创建时间"
              unlink-panels
              type="daterange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
            ></el-date-picker>
          </el-form-item>
          <el-form-item :inline="true" style="float: right;">
            <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>

        <el-timeline>
          <el-timeline-item
            v-for="(dynamic, index) in dynamics"
            :key="index"
            :timestamp="dynamic.createTime"
            placement="top"
          >
            <el-card>
              <div style="text-align:right;">
                <el-button
                  type="text"
                  @click="toTop(dynamic.dynamicId, true)"
                  style="color: #eccc68;"
                >置顶</el-button>
                <el-button
                  type="text"
                  v-if="dynamic.topTime != null"
                  @click="toTop(dynamic.dynamicId, false)"
                  style="color: #ff7f50;"
                >取消置顶</el-button>
                <el-button
                  type="text"
                  v-if="dynamic.status === '1'"
                  @click="changeStatus(dynamic.dynamicId, '0')"
                  style="color: #ff6b81;"
                >公开</el-button>
                <el-button
                  type="text"
                  v-else-if="dynamic.status === '0'"
                  @click="changeStatus(dynamic.dynamicId, '1')"
                  style="color: #a4b0be;"
                >私人</el-button>
                <el-button
                  type="text"
                  style="color: red;"
                  @click="deleteDynamic(dynamic.dynamicId)"
                >删除</el-button>
              </div>
              <div :innerHTML="dynamic.dynamic"></div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <div style="text-align: center;">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="5"
            :hide-on-single-page="true"
            v-model:currentPage="queryParams.current"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="发布" name="release">
        <div ref="editor"></div>
        <el-button type="primary" style="margin: 10px;width: 15%;float:right;" @click="release">发布</el-button>
        <div :innerHTML="content.html" style="margin-top: 60px;"></div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-model="dialogVisible" width="20%" :show-close="false">
      <div style="text-align: center;">
        <el-button class="private" circle @click="commit('0')">私人</el-button>
        <el-button class="private" circle @click="commit('1')">公开</el-button>
      </div>
      <div style="text-align: center;">
        <el-checkbox v-model="isTop" label="是否置顶" size="large" />
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import WangEditor from 'wangeditor';
import { onMounted, reactive, ref, onBeforeUnmount } from 'vue'
import { add, pageList, updateStatus, deleteById, changeTop } from '@/api/dynamic'
import type { DynamicType, Dynamic } from '@/api/types/dynamic'

const editor = ref()
const content = reactive({
  html: '',
  text: ''
})

const queryParams = reactive<DynamicType>({
  current: 1,
  size: 5,
  status: undefined,
  dateRange: undefined
})

const total = ref(0)

const shortcuts: [] = []

const dialogVisible = ref(false)

const activeName = ref('manage')

const dynamics = ref<Dynamic[]>()

let instance: WangEditor

let isTop = ref(false)

onMounted(() => {
  loadList()
  instance = new WangEditor(editor.value);
  instance.config.onchange = (newHtml: any) => {
    content.html = newHtml
  }
  instance.config.zIndex = 1
  instance.create()
})

onBeforeUnmount(() => {
  instance.txt.clear()
});

const release = () => {
  dialogVisible.value = true
}

const commit = async (status: string) => {
  const ok = await add({ content: content.html, status, top: isTop.value })
  if (ok) {
    ElMessage({
      message: '添加成功',
      type: 'success',
    })
  }
  instance.txt.clear()
  loadList()
  pageList(queryParams)
  activeName.value = 'manage'
  dialogVisible.value = false
  isTop.value = false
}

const loadList = async () => {
  const page = await pageList(queryParams)
  dynamics.value = page.records
  total.value = page.total
  console.log(dynamics.value)
}

const handleCurrentChange = (val: number) => {
  queryParams.current = val
  loadList()
}

const changeStatus = async (id: number, status: string) => {
  const ok = await updateStatus(id, status)
  if (ok) {
    ElMessage({
      message: '修改成功',
      type: 'success',
    })
  }
  loadList()
}

const toTop = async (id: number, status: boolean) => {
  const ok = await changeTop(id, status)
  if (ok) {
    ElMessage({
      message: '修改成功',
      type: 'success',
    })
  }
  loadList()
}

const deleteDynamic = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '是否要删除动态',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const ok = await deleteById(id)
    if (ok) {
      loadList()
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
    } else {
      ElMessage({
        message: '请选择删除数据',
        type: 'error',
      })
    }
  } catch (err) {

  }

  loadList()
}

const handleSearch = () => {
  loadList()
}

const handleReset = () => {
  queryParams.current = 1
  queryParams.dateRange = undefined
  queryParams.status = undefined
  loadList()
}

</script>

<style lang="sass" scoped>

.private
  width: 80px
  height: 80px
  margin: 10px

:deep(.el-dialog__header)
  padding: 0
</style>